package com.nineclock.document.service.impl;
import java.util.Comparator;
import java.util.Date;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.entity.Result;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.document.dto.DocFileHistoryDto;
import com.nineclock.document.mapper.DocFileHistoryMapper;
import com.nineclock.document.pojo.DocFileHistory;
import com.nineclock.document.service.DocFileHistoryService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DocFileHistoryServiceImpl implements DocFileHistoryService {

    @Autowired(required = false)
    private DocFileHistoryMapper fileHistoryMapper;

    @Autowired
    private SysCompanyUserFeign companyUserFeign;


    /**
     * 查询文件历史记录
     * @param fileId
     * @return
     */
    @Override
    public List<DocFileHistoryDto> queryHistory(@PathVariable Long fileId) {
        //校验数据
        if (fileId==null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        LambdaQueryWrapper<DocFileHistory> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(DocFileHistory::getFileId,fileId);
        wrapper.orderByDesc(DocFileHistory::getOperateTime);
        List<DocFileHistory> fileHistoryList = fileHistoryMapper.selectList(wrapper);
        List<DocFileHistoryDto> docFileHistoryDtoList = fileHistoryList.stream().map(docFileHistory -> {
            Long operateUserId = docFileHistory.getOperateUserId();
            SysCompanyUserDTO companyUserDTO = companyUserFeign.queryCompanyUserById(operateUserId).getData();
            DocFileHistoryDto docFileHistoryDto = new DocFileHistoryDto();
            docFileHistoryDto.setFileName(docFileHistory.getFileName());
            docFileHistoryDto.setOperateUserId(companyUserDTO.getId());
            docFileHistoryDto.setOperateTime(docFileHistory.getOperateTime());
            docFileHistoryDto.setIsCreate(docFileHistory.getIsCreate());
            docFileHistoryDto.setContent(docFileHistory.getContent());
            docFileHistoryDto.setUserName(companyUserDTO.getUserName());
            return docFileHistoryDto;
        }).collect(Collectors.toList());

        return docFileHistoryDtoList;
    }
}
